package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.vo.ResumesImportVo;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.*;
import com.jinzhi.jzweb.utils.FileUtil;
import com.jinzhi.oss.service.OssService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 简历
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@Slf4j
@RequestMapping("/jzweb/resumes")
public class ResumesController extends BaseController {
	@Autowired
	private ResumesService resumesService;
	@Autowired
	private UserService userService;
	@Autowired
	private FocusOnResumesService focusOnResumesService;
	@Autowired
	private DictService dictService;
	@Autowired
	private RecruitmentNewsService recruitmentNewsService;
	@Autowired
	private OrganizationNewsService organizationNewsService;
	@Autowired
	private ApplicationRecordService applicationRecordService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private OssService ossService;
	@GetMapping()
	@RequiresPermissions("jzweb:resumes:resumes")
	String Resumes(){
	    return "jzweb/resumes/resumes";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:resumes:resumes")
	public Result<Page<ResumesDO>> list(ResumesDO resumesDTO){
        Wrapper<ResumesDO> wrapper = new EntityWrapper<ResumesDO>().orderBy("id", false);
		if (StringUtils.isNotBlank(resumesDTO.getUserName())&&resumesDTO.getUserName()!=null&&resumesDTO.getUserName()!=""){
			Wrapper<UserDO> Wrapper = new EntityWrapper<UserDO>().like("name",resumesDTO.getUserName());
			List<UserDO>  userDOS = userService.selectList(Wrapper);
			String str = "";
			for (UserDO userDO : userDOS){
				str = str + userDO.getId() + ",";
			}
			wrapper.and();
			if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
				wrapper.in("user_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("user_id",null);
			}
		}
		if (resumesDTO.getDesiredOccupation() != null){
			wrapper.like("desired_occupation",resumesDTO.getDesiredOccupation());
		}

		//查询用户角色
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			wrapper.eq("state",0);
		}else{
			if (resumesDTO.getState() != null){
				wrapper.eq("state",resumesDTO.getState());
			}
		}

        Page<ResumesDO> page = resumesService.selectPage(getPage(ResumesDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			ResumesDO obj = (ResumesDO) page.getRecords().get(i);
			if (obj.getUserId() != null) {
				UserDO userDO = userService.getByUserId(obj.getUserId());
				if (userDO != null) {
					if(StringUtils.isNotBlank(userDO.getName())){
						obj.setUserName(userDO.getName());
					}else{
						obj.setUserName(userDO.getUsername());
					}
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:resumes:add")
	String add(){
	    return "jzweb/resumes/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:resumes:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ResumesDO resumes = resumesService.selectById(id);
		model.addAttribute("resumes", resumes);
	    return "jzweb/resumes/edit";
	}

	@GetMapping("/info/{id}")
	@RequiresPermissions("jzweb:resumes:resumes")
	String info(@PathVariable("id") Long id, Model model) {
		ResumesDO resumes = resumesService.selectById(id);
		if (resumes.getUserId() != null) {
			UserDO userDO = userService.getByUserId(resumes.getUserId());
			if (userDO != null) {
				resumes.setUserName(userDO.getUsername());
				resumes.setMobile(userDO.getMobile());
				resumes.setSex(userDO.getSex());
				resumes.setHeadPortrait(userDO.getHeadPortrait());
				resumes.setPoliticalAffiliation(userDO.getPoliticalAffiliation());
				resumes.setLiveAddress(userDO.getLiveAddress());
				resumes.setEmail(userDO.getEmail());
				resumes.setDateOfBirth(userDO.getDateOfBirth());
			}
		}
		model.addAttribute("resumes", resumes);
		return "jzweb/resumes/info";
	}
	
	@Log("添加简历")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:resumes:add")
	public Result<String> save( ResumesDO resumes){
		resumesService.insert(resumes);
        return Result.ok();
	}


	@GetMapping("/resumesadd")
	@RequiresPermissions("jzweb:resumes:resumesadd")
	String resumesAdd(Model model,String resuId){
		Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().orderBy("name");
		orWrapper.eq("type",5);
		List<OrganizationNewsDO> list=organizationNewsService.selectList(orWrapper);

		model.addAttribute("resumes", list);
		model.addAttribute("resuId", resuId);
		return "jzweb/resumes/resumesadd";
	}

	@Log("导出简历信息")
	@GetMapping("/exportResumes")
	@ResponseBody
	@RequiresPermissions("jzweb:resumes:export")
	public void exportResumes(HttpServletRequest request, HttpServletResponse response,String[] rows,Integer pageNum) throws Exception {
		resumesService.exportResumes(request,response,rows,pageNum);
	}


	/*
	* 新增推荐
	 */
	@Log("选择推荐简历")
	@ResponseBody
	@PostMapping("/resumesSave")
	@RequiresPermissions("jzweb:resumes:resumesadd")
	public ApiResult<?> resumesSave( String id,String resuId){
		//1.根据token获取用户登录数据

		if(StringUtils.isBlank(id)){
			return ApiResult.lack("");//缺少参数
		}
		//查询简历信息
		ResumesDO resumesDO=resumesService.selectById(resuId);

			//查询是否存在这个用户
			UserDO userDO=	userService.getByUserId(resumesDO.getUserId());
			if(userDO==null){
				return ApiResult.success("该用户不存在！");
			}

			if(resumesDO != null){

				Wrapper<ApplicationRecordDO> orWrapper1 = new EntityWrapper<ApplicationRecordDO>().orderBy("id");
				orWrapper1.eq("user_id",resumesDO.getUserId());
				orWrapper1.eq("rnews_id",id);

				List<ApplicationRecordDO> list=applicationRecordService.selectList(orWrapper1);

				if(list.size()==0){
					ApplicationRecordDO applicationRecordDO1 = new ApplicationRecordDO();
					applicationRecordDO1.setUserId(resumesDO.getUserId());//用户id
					applicationRecordDO1.setOrgId( Long.parseLong(id));//机构id


					Wrapper<RecruitmentNewsDO> orWrapper1s = new EntityWrapper<RecruitmentNewsDO>().orderBy("id");
					orWrapper1s.eq("org_id",id);

					List<RecruitmentNewsDO> listnews=recruitmentNewsService.selectList(orWrapper1s);

					if(listnews.size()==0){
						return ApiResult.success("该企业未发布招聘信息！");
					}
					applicationRecordDO1.setRnewsId(listnews.get(0).getId());//招聘岗位id

					applicationRecordDO1.setAppTime(new Date());//应聘时间
					applicationRecordDO1.setCreaterDate(new Date());//创建时间
					applicationRecordDO1.setState(2);//默认沟通中
					applicationRecordDO1.setType(1);
					boolean b = applicationRecordService.insert(applicationRecordDO1);
					if(b){


						return ApiResult.success("投递成功，请静候佳音！");
					}else{
						return ApiResult.fail("投递失败，请刷新重试！");
					}
				}else{
					return ApiResult.fail("您已投递，请勿重复！");
				}
			}else{
				return ApiResult.fail("信息错误，请刷新重试！");
			}



	}



	@Log("修改简历")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:resumes:edit")
	public Result<String>  update( ResumesDO resumes){
		boolean update = resumesService.updateById(resumes);
		return update ? Result.ok() : Result.fail();
	}

	@Log("关注简历")
	@PostMapping( "/focusRe")
	@ResponseBody
	@RequiresPermissions("jzweb:resumes:add")
	public Result<String>  focusRe( Long id){
		ResumesDO resumesDO = resumesService.selectById(id);
		FocusOnResumesDO focusOnResumesDO = new FocusOnResumesDO();

		focusOnResumesDO.setOrgId(this.getUser().getOrgId());//机构id
		focusOnResumesDO.setUserId(resumesDO.getUserId());//用户id
		focusOnResumesDO.setResumeId(id);//简历id
		focusOnResumesDO.setState(0);//默认正常

		boolean b;
		FocusOnResumesDO focusOnResumesDO1 = focusOnResumesService.selMaxTime(this.getUser().getOrgId());
		if(focusOnResumesDO1 != null){
			if(focusOnResumesDO1.getResidues() <= 0){
				return Result.fail("您关注简历的次数为0,请前往关注简历页面购买后继续！");
			}else{
				focusOnResumesDO.setLookOvers(focusOnResumesDO1.getLookOvers() + 1);//已查看次数
				focusOnResumesDO.setResidues(focusOnResumesDO1.getResidues() - 1);//剩余查看次数
				b = focusOnResumesService.insert(focusOnResumesDO);
			}
		}else{
			Integer focNum = 10;
			Map map = new HashMap();
			map.put("name", "关注简历免费次数");
			map.put("type", "focus_res");
			String focuson = dictService.selDicBy(map);
			if (StringUtils.isNotBlank(focuson)) {
				//判断是否为数字
				if (IdCardUtil.isNumeric(focuson)) {
					focNum = Integer.parseInt(focuson);
				}
			}

			focusOnResumesDO.setLookOvers(1);//已查看次数
			focusOnResumesDO.setResidues(focNum - 1);//剩余查看次数
			b = focusOnResumesService.insert(focusOnResumesDO);
		}

		if(b){
			return Result.ok();
		}else{
			return Result.fail();
		}
	}
	
	@Log("删除简历")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:resumes:remove")
	public Result<String>  remove( Long id){
		resumesService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除简历")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:resumes:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		resumesService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}






	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<ResumesImportVo> list = new LinkedList<>();
		//导出操作
		// 配置导出参数：启用 @Excel 注解定义的标题行
		ExportParams exportParams = new ExportParams();
		exportParams.setCreateHeadRows(true); // 启用默认标题行（由 @Excel 注解定义）
		exportParams.setSheetName("简历信息导入模板"); // 设置 Sheet 名称
		EasyPoiUtil.exportExcel1(list, "简历信息导入模板", "简历信息导入模板", ResumesImportVo.class, "简历信息导入模板.xlsx", response);

	}
	@Log("导入招聘信息")
	@ResponseBody
	@PostMapping("/import")
//    @RequiresPermissions("jzweb:recruitmentNews:import")
	public Result<?> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
		// 第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		// 第二步--解析文件获得数据
		List<ResumesImportVo> list = EasyPoiUtil.importExcel(file, 0, 1, ResumesImportVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}

		// 第三步--判断导入人员身份，获取导入人员信息
		int startRow = 2;
		int cout = 1; // 错误信息计数
		List<ResumesDO> resumesDOS = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		FileUtil fileUtil = new FileUtil();
		for (int i = 0; i < list.size(); i++) {
			UserDO rrUserDo = null;
			UserDO rsUserDo = null;
			StringBuilder sb = new StringBuilder();
			// 第一步验证是否存在空值
			if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getName())) {
				sb.append("第" + (i + startRow) + "行姓名未填写，请完善！" + ";");
			} else {
				if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getSex())) {
					sb.append("第" + (i + startRow) + "行性别未填写，请完善！" + ";");
				} else  {
					if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getDateOfBirth())){
						sb.append("第" + (i + startRow) + "行请选择出生日期未填写，请完善！" + ";");
					}else {
						if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getNativePlace())) {
							sb.append("第" + (i + startRow) + "行籍贯未填写，请完善！" + ";");
						}else {
							if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getNation())) {
								sb.append("第" + (i + startRow) + "行民族未填写，请完善！" + ";");
							}else {
								if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getHealthStatus())) {
									sb.append("第" + (i + startRow) + "行您的健康状况未填写，请完善！" + ";");
								}else {
									if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getPoliticalAffiliation())) {
										sb.append("第" + (i + startRow) + "行政治面貌未填写，请完善！" + ";");
									}else {
										if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getHeight())) {
											sb.append("第" + (i + startRow) + "行身高未填写，请完善！" + ";");
										}else {
											if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getMobile())) {
												sb.append("第" + (i + startRow) + "行联系电话（个人电话）未填写，请完善！" + ";");
											}else {
												if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getParentPhone())) {
													sb.append("第" + (i + startRow) + "行联系电话（家长电话）未填写，请完善！" + ";");
												}else {
													if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getSkills())) {
														sb.append("第" + (i + startRow) + "行个人具备技能及素养未填写，请完善！" + ";");
													}else {
														if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getExpectedSalary())) {
															sb.append("第" + (i + startRow) + "行个人期待薪资与福利未填写，请完善！" + ";");
														}else {
															if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getHomeAddress())) {
																sb.append("第" + (i + startRow) + "行家庭地址未填写，请完善！" + ";");
															}else {
																if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getMajor())) {
																	sb.append("第" + (i + startRow) + "行所学专业未填写，请完善！" + ";");
																}else {
																	if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getCertificates())) {
																		sb.append("第" + (i + startRow) + "行所获证书未填写，请完善！" + ";");
																	}else {
																		if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getGraduationTime())) {
																			sb.append("第" + (i + startRow) + "行实习/毕业时间未填写，请完善！" + ";");
																		}else {
																			if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getHonors())) {
																				sb.append("第" + (i + startRow) + "行在校所获荣誉未填写，请完善！" + ";");
																			}else {
																				if (org.apache.commons.lang.StringUtils.isBlank(list.get(i).getGraduatedFrom())) {
																					sb.append("第" + (i + startRow) + "行所在学校未填写，请完善！" + ";");
																				}else {
																					//第五步根据手机号码获取用户信息并判断，如没有则新建，如果则返回信息
																					UserDO userDO = userService.findOneByKv("mobile", list.get(i).getMobile().trim());

																					if (userDO != null) {

																						if (userDO.getName() != null) {
																							if (!userDO.getName().equals(list.get(i).getName().trim())) {
																								sb.append("第" + (i + startRow) + "行考生已注册，但姓名不一致，请修改后重试！" + ";");
																							}
																						} else {
																							userDO.setName(list.get(i).getName());
																						}

//                                                                    userDO.setOrgId(this.getUser().getOrgId());
//                                                                    userDO.setOrgName(this.getUser().getOrgName());
																						List<Long> roleIds = userRoleService.listRoleId(userDO.getId());

																						if (roleIds != null && roleIds.size() > 0) {
																							userDO.setroleIds(roleIds);
																						} else {
																							List<Long> list11 = new ArrayList<>();
																							list11.add(56L);
																							userDO.setroleIds(list11);
																						}
																						userFormat(list.get(i),userDO); //新字段添加 2022-10-31
																						userService.updateById(userDO);
																						rsUserDo = userDO;
																					} else {
																						UserDO userDO1 = new UserDO();
																						userFormat(list.get(i),userDO1); //新字段添加 2022-10-31
																						userDO1.setUsername(list.get(i).getMobile().trim());
																						userDO1.setName(list.get(i).getName().trim());
																						userDO1.setMobile(list.get(i).getMobile().trim());

																						//初始密码设为身份证号后六位
																						//String password = list.get(i).getIdCard().trim().substring(list.get(i).getIdCard().trim().length() - 6);
																						//初始密码设为123456
																						String password = "abc123456";
																						String salt = UUIDUtils.get();
																						String encodePasswd = PasswdUtils.get(password, salt);
																						userDO1.setSalt(salt);
																						userDO1.setPassword(encodePasswd);
																						userDO1.setType(0);//默认个人会员
																						userDO1.setMoney(BigDecimal.valueOf(0.0));//默认0元
																						userDO1.setGmtCreate(new Date());
																						userDO1.setGmtModified(userDO1.getGmtCreate());
																						userDO1.setStatus(1);//默认正常
																						userDO1.setSex("男".equals(list.get(i).getSex()) ? 1L : 0L);//性别，默认未知

//                                                                    userDO1.setOrgId(this.getUser().getOrgId());
//                                                                    userDO1.setOrgName(this.getUser().getOrgName());

																						List<Long> roleIds = userRoleService.listRoleId(userDO1.getId());
																						if (roleIds != null && roleIds.size() > 0) {
																							userDO1.setroleIds(roleIds);
																						} else {
																							List<Long> list11 = new ArrayList<>();
																							list11.add(56L);
																							userDO1.setroleIds(list11);
																						}
																						rrUserDo = userDO1;
																					}
																				}

																			}

																		}
																	}
																}
															}
														}

													}
												}
											}
										}
									}
								}
							}
						}
					}
				}

			}

			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
				cout += 1;
			} else {
				if (rrUserDo != null) {
					boolean cc = userService.insertNoPW(rrUserDo);
					if (!cc) {
						log.info("第" + (i + startRow) + "行用户信息导入失败，建议删除重新导入！" + ";");
					}
				} else {
					boolean cc = userService.updateById(rsUserDo);
					if (!cc) {
						log.info("第" + (i + startRow) + "行用户信息修改失败，请查看！" + ";");
					}
				}


				ResumesDO resumesDO = new ResumesDO();
				if (rrUserDo!=null){
					resumesDO.setUserId(rrUserDo.getId());
				}else {
					if (rsUserDo != null) {
						resumesDO.setUserId(rsUserDo.getId());
					}
				}

				resumesDO.setState(0);
				resumesDO.setMobile(list.get(i).getMobile());
				resumesDO.setCertificate(list.get(i).getCertificates());
				resumesDO.setSex("男".equals(list.get(i).getSex()) ? 1L : 0L);
				resumesDO.setSkills(list.get(i).getSkills());
				resumesDO.setGraduatedFrom(list.get(i).getGraduatedFrom());
				resumesDO.setGraduationTime(list.get(i).getGraduationTime());
				resumesDO.setParentPhone(list.get(i).getParentPhone());
				resumesDO.setHomeAddress(list.get(i).getHomeAddress());
				resumesDO.setHeight(list.get(i).getHeight());
				resumesDO.setCertificates(list.get(i).getCertificates());
				
				// 处理证书图片上传
				if (StringUtils.isNotBlank(list.get(i).getCertificatePhotos())) {
					List<String> ossUrls = Arrays.stream(list.get(i).getCertificatePhotos().split(","))
							.map(localPath -> {
								File file1 = new File(localPath);
								MultipartFile multipartFile = null;
								try {
									multipartFile = new MockMultipartFile(file1.getName(), new FileInputStream(file1));
								} catch (IOException e) {
									throw new RuntimeException(e);
								}
								return ossService.uploadFileOssName(multipartFile);
							})
							.collect(Collectors.toList());
					resumesDO.setCertificatePhotos(String.join(",", ossUrls));
				}
				resumesDO.setIntendedCity(list.get(i).getIntendedCity());
				resumesDO.setIsAdjustCity("接受".equals(list.get(i).getIsAdjustCity())?1:0);
				resumesDO.setIntendedPosition(list.get(i).getIntendedPosition());
				resumesDO.setIsAdjustPosition("接受".equals(list.get(i).getIsAdjustPosition())?1:0);
				resumesDO.setHonors(list.get(i).getHonors());
				resumesDO.setSocialPractice(list.get(i).getSocialPractice());
				resumesDO.setSelfIntroVideo(list.get(i).getSelfIntroVideo());
				resumesDO.setNativePlace(list.get(i).getNativePlace());
				resumesDO.setUnderstandingPosition(list.get(i).getUnderstandingPosition());
				resumesDO.setParentOpinion(list.get(i).getParentOpinion());
				resumesDO.setPersonalGrowthPlan(list.get(i).getPersonalGrowthPlan());
				resumesDO.setSubmitter(list.get(i).getSubmitter());
				resumesDO.setHealthStatus(list.get(i).getHealthStatus());
				resumesDO.setExpectedSalary(list.get(i).getExpectedSalary());
				resumesDO.setCreaterDate(new Date());
				resumesDOS.add(resumesDO);
			}
		}
		if (list1.size() == 0) {
			boolean c = resumesService.insertOrUpdateBatch(resumesDOS, resumesDOS.size());
			if (c) {
				return Result.ok("成功导入" + resumesDOS.size() + "条数据");
			} else {
				return Result.fail("简历信息添加错误，请稍后重试或联系管理员");
			}
		} else {
			//导入失败，删除已导入的图片
			for (int fi = 0; fi < list.size(); fi++) {
				if (StringUtils.isNotBlank(list.get(fi).getCertificatePhotos())) {
					String url = list.get(fi).getCertificatePhotos().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
					String imgUrl = url.replace("\\", "/");
					boolean b1 = fileUtil.DeleteFolder(imgUrl);
					log.info("导入简历失败删除证书照片第" + (fi + 1) + "张，情况：" + b1);
				}
			}
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			EhCacheUtil.put("resums" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
	}

	/**
	 * 证书导入 user类格式化
	 * @param trainingCerVo
	 * @param userDO
	 * @return
	 */
	private UserDO userFormat(ResumesImportVo trainingCerVo, UserDO userDO){

		if (StringUtils.isNotBlank(trainingCerVo.getSex())){
			//如果性别不为空
			if (userDO.getSex() == null) {
				userDO.setSex("男".equals(trainingCerVo.getSex()) ? 1L : 0L);
			}
		}

		if (StringUtils.isNotBlank(trainingCerVo.getMajor())){
			//专业
			if (StringUtils.isBlank(userDO.getMajor())) {
				userDO.setMajor(trainingCerVo.getMajor());
			}
		}

		if (StringUtils.isNotBlank(trainingCerVo.getHomeAddress())){
			//现居住地址
			if (StringUtils.isBlank(userDO.getLiveAddress())) {
				userDO.setLiveAddress(trainingCerVo.getHomeAddress());
			}
		}
		if (StringUtils.isNotBlank(trainingCerVo.getDateOfBirth())){
			//出生年月
			if (StringUtils.isBlank(userDO.getDateOfBirth())) {
				userDO.setDateOfBirth(trainingCerVo.getDateOfBirth());
			}
		}
		return userDO;
	}

	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
//	@RequiresPermissions("jzweb:resumes:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("简历信息导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("resums" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}
}
